package org.springframework.core.convert.support;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

/**
 * @Name StringToNumberConverterFactory
 * @Description: String -> Number 工厂类型转换器 [实现] 类
 * @Version v1.0.0
 * @Author: lichao
 * @Date: 2024-04-11 14:56:39
 **/
public class StringToNumberConverterFactory implements ConverterFactory<String, Number> {
    @Override
    public <T extends Number> Converter<String, T> getConverter(Class<T> targetType) {
        return new StringToNumber<T>(targetType);
    }

    private static final class StringToNumber<T extends Number> implements Converter<String, T> {
        private final Class<T> targetType;

        public StringToNumber(Class<T> targetType) {
            this.targetType = targetType;
        }

        @Override
        public T convert(String source) {
            if (source.length() == 0) return null;
            if (targetType.equals(Integer.class)) {
                return (T) Integer.valueOf(source);
            }
            if (targetType.equals(Long.class)) {
                return (T) Long.valueOf(source);
            }
            // TODO 其他数字类型
            else
                throw new IllegalArgumentException("String {" + source + "} 不能被转换成目标类型 [" + targetType + "]");
        }
    }

}

